package com.zmx.oauth2.config;

import com.zmx.oauth2.user.entity.Member;
import com.zmx.oauth2.user.entity.SysUser;
import com.zmx.oauth2.user.repository.MemberRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description: 实现用户身份验证
 * @ClassName: KiteUserDetailsService
 * @Author zhaomxr
 * @Date 2021-11-08 15:08
 */
@Slf4j
@Component
public class KiteUserDetailsService implements UserDetailsService {

    @Autowired
    public PasswordEncoder passwordEncoder;
    @Autowired
    private MemberRepository memberRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("username is:" + username);

        //为了同时使用真正登录认证 与本地测试登录，以用户名做个假认证
        if (Objects.equals("zhaomx", username)) {
            // 用户角色也应在数据库中获取
            String role = "ROLE_ADMIN";
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority(role));
            return new User("zhaomx", "$2a$10$KWmUwADshF/FXWuwEnfVkeh0qS8uiCNqGV./iha37bKR8/kXNxCdi", authorities);
        } else {
            Member member = memberRepository.findByOpenid(username);
            //查询用户是否存在
            if (member == null) {
                throw new UsernameNotFoundException("the member is not found");
            } else {
                // 用户角色也应在数据库中获取
                String role = "ROLE_ADMIN";
                List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                authorities.add(new SimpleGrantedAuthority(role));
                return new User(member.getOpenid(), passwordEncoder.encode(member.getOpenid()), authorities);
            }
        }
    }
}
